#include<targets/lpc21xx.h>
#include <ctl_api.h> 
#include "clock.h"

clock_time_t ClockTimer;

void timerISR(void);
/***********************************************************************/
/** \brief initialise the clock.
 *
 * Description: initialise timer0 on the LPC2106. Timer shall fire every
 *              100mS. Assume Peripheral Clock = 29.4912 MHz 
 *              
 *              
 * \author Iain Derrington
 * \date 0.1 01/07/2007
 */
/**********************************************************************/
void clock_init(void)
{
  ClockTimer=0;
  
  // Setup VIC to fire on timer0 IRQ's
  VICVectAddr0 = (int)&timerISR;    //address of IRQ
  VICVectCntl0 = 0x0024;            // Slot 0 assigned to irq 4 (timer 0 )
  VICIntEnable = 0x0010;
  
  /*ctl_set_isr(4, 0, CTL_ISR_TRIGGER_FIXED, timerISR, 0);
  ctl_unmask_isr(4);*/

  // Set up timer to fire periodic IRQ
  T0PR = 29491200/20;       // Debug setup so that T0TC increment every 100 msecond
  T0MCR = 3;                // Generate an interrupt on Match 0 and clear timer 0
  T0MR0 = 1;                // 
  T0TCR = 1;                // start timer
} 

/***********************************************************************/
/** \brief Returns counter value.
 *
 * \author Iain Derrington
 * \return clock_time_t
 * \date 
 */
/**********************************************************************/
clock_time_t clock_time(void)
{
  return ClockTimer;
}

/***********************************************************************/
/** \brief ISR for Timer.
 *
 * Description: Increments the system clock     
 * \author Iain Derrington
 * \date WIP
 */
/**********************************************************************/
void timerISR(void)
{
  ClockTimer++;
  
  T0IR = 1;   //clear irq
  VICVectAddr = 0;
}
